import json
import random
import socket
import threading
import time


def client(name):  # 客户端
    # socket.AF_INET:基于IPV4;socket.SOCK_STREAM:基于TCP/IP
    client_ = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    client_.connect(('localhost', 8000))  # 监听8000端口

    while True:
        message = str(''.join(random.choices('abcdefghijklmnopqrstuvwxyz0123456789', k=5)))
        client_.send(json.dumps({'name': name, 'message': message}).encode('utf-8'))
        data = client_.recv(1024)
        print(f"{name}来自服务端的：" + data.decode('utf-8'))
        timeout = random.randint(0, 2)  # 设置随机睡眠
        time.sleep(timeout)


if __name__ == '__main__':
    c1 = threading.Thread(target=client, args=('client1',))
    c2 = threading.Thread(target=client, args=('client2',))
    c3 = threading.Thread(target=client, args=('client3',))
    for c in [c1, c2, c3]:
        c.start()
